package io.renren.com.qywt.controller;

import cn.hutool.core.util.ObjectUtil;
import io.renren.commons.log.annotation.LogOperation;
import io.renren.commons.tools.constant.Constant;
import io.renren.commons.tools.page.PageData;
import io.renren.commons.tools.utils.Result;
import io.renren.commons.tools.utils.ExcelUtils;
import io.renren.commons.tools.validator.AssertUtils;
import io.renren.commons.tools.validator.ValidatorUtils;
import io.renren.commons.tools.validator.group.AddGroup;
import io.renren.commons.tools.validator.group.DefaultGroup;
import io.renren.commons.tools.validator.group.UpdateGroup;
import io.renren.com.qywt.dto.AftersaleSupplierDTO;
import io.renren.com.qywt.excel.AftersaleSupplierExcel;
import io.renren.com.qywt.service.AftersaleSupplierService;
import io.renren.dto.SysRegionDTO;
import io.renren.feign.RegionFeignClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
* 供应商信息表
*
* @author jiaohj 15110414840@139.com
* @since 3.0 2022-11-12
*/
@RestController
@RequestMapping("supplier")
@Api(tags="供应商信息表")
public class AftersaleSupplierController {
    @Autowired
    private AftersaleSupplierService supplierService;
    @Autowired
    private RegionFeignClient regionFeignClient;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @PreAuthorize("hasAuthority('aftersale:supplier:page')")
    public Result<PageData<AftersaleSupplierDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<AftersaleSupplierDTO> page = supplierService.page(params);
        return new Result<PageData<AftersaleSupplierDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @PreAuthorize("hasAuthority('aftersale:supplier:info')")
    public Result<AftersaleSupplierDTO> get(@PathVariable("id") Long id){
        AftersaleSupplierDTO data = supplierService.get(id);
        if(StringUtils.isNotBlank(data.getRegionCodes())){
            List<Long> regionCodeList=new ArrayList<>();
            for(String regionCode: data.getRegionCodes().split(",")){
                regionCodeList.add(Long.parseLong(regionCode));
            }
            data.setRegionCodeList(regionCodeList);
        }
        return new Result<AftersaleSupplierDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @PreAuthorize("hasAuthority('aftersale:supplier:save')")
    public Result save(@RequestBody AftersaleSupplierDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        if(ObjectUtil.isNotNull(dto.getRegionCodeList())&&!dto.getRegionCodeList().isEmpty()){
            for(Long id:dto.getRegionCodeList()){
                Result<SysRegionDTO> result=regionFeignClient.getById(id);
                if(ObjectUtil.isNotNull(result.getData())){
                    SysRegionDTO sysRegionDTO=result.getData();
                    if(sysRegionDTO.getTreeLevel()==1){
                        dto.setProvinceCode(sysRegionDTO.getId());
                        dto.setProvinceName(sysRegionDTO.getName());
                    }else if(sysRegionDTO.getTreeLevel()==2){
                        dto.setCityCode(sysRegionDTO.getId());
                        dto.setCityName(sysRegionDTO.getName());
                    }else if(sysRegionDTO.getTreeLevel()==3){
                        dto.setCountyCode(sysRegionDTO.getId());
                        dto.setCountyName(sysRegionDTO.getName());
                    }
                }
            }
            dto.setRegionCodes(StringUtils.join(dto.getRegionCodeList(),","));
        }
        supplierService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @PreAuthorize("hasAuthority('aftersale:supplier:update')")
    public Result update(@RequestBody AftersaleSupplierDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        supplierService.update(dto);
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @PreAuthorize("hasAuthority('aftersale:supplier:delete')")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        supplierService.delete(ids);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @PreAuthorize("hasAuthority('aftersale:supplier:export')")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<AftersaleSupplierDTO> list = supplierService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, "供应商信息表", list, AftersaleSupplierExcel.class);
    }

}